<template>
  <div class="box">
    <div class="header-box">
      <a-alert type="warning">
        <template #description>
          <p>
            无团队的招商专员将无法在佣金结算中计算佣金，已经结算的不受影响。
          </p>
        </template>
      </a-alert>
    </div>

    <a-table
        :dataSource="dataList"
        class="person-table"
        :columns="columns"
        :loading="loading"
        rowKey="id"
        :pagination="pagination"
        @change="handleTableChange"
        @expand="getSubData"
        :expandedRowKeys="expandedRowKeys"
    >
      <template #title>
        <div class="flex justify-between header-clue">
          <div class="flex-1">
            <a-form layout="vertical">
              <a-row :gutter="8" :wrap="true" type="flex">
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索招商人名称"
                        v-model:value="searchParams.name"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索招商人电话"
                        v-model:value="searchParams.tel"
                    />
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item label="">
                    <a-space>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="getDataList(true)">
                        搜索
                      </a-button>
                    </a-space>
                  </a-form-item>
                </a-col>
                <a-col style="margin-left: auto">
                  <a-button type="primary" @click="addPersonnel"
                  >+新增招商人员
                  </a-button
                  >
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key == 'clue_num'">
          <a-button type="link" @click="showClueList(record.uid)">{{
              record.clue_num
            }}
          </a-button>
        </template>
        <template v-if="column.key == 'customer_num'">
          <a-button type="link" @click="showCustomerList(record.uid)">{{
              record.customer_num
            }}
          </a-button>
        </template>
        <template v-if="column.key == 'contract_num'">
          <a-button type="link" @click="toContractInfo(record.uid)">{{
              record.contract_num
            }}
          </a-button>
        </template>
        <template v-if="column.key === 'name'">
          <span>
            <span
                :class="record?.uid ? 'link' : ''"
                @click="showUserInfo(record.uid)"
            >
              {{ record?.userInfo?.final_name || "--" }}
            </span>
            <a-tag v-if="record.role == 1" color="blue" style="margin-left: 4px"
            >招商经理</a-tag
            >
          </span>
        </template>
        <template v-if="column.key === 'teamName'">
          <a-space>
            <span>
              {{ record?.team?.name || "--" }}
            </span>
            <a-button
                type="link"
                :disabled="record.role == 1"
                @click.stop="editTeam(record)"
            >
              <FormOutlined/>
            </a-button>
          </a-space>
        </template>
        <template v-if="column.key === 'action'">
          <a-button
              type="link"
              :disabled="record.role == 1"
              danger
              @click.stop="handleRemovePersonnel(record)"
          >移除人员
          </a-button
          >
        </template>
      </template>
    </a-table>

    <!--  新增招商人员  -->
    <AddTeamPersonnel
        :visible="addVisible"
        fromType="person"
        :villageOptions="villageOptions"
        @handleCancel="addVisible = false"
        @success="handleAddSuccess"
    />

    <!--  人员设置招商团队  -->
    <SetBusinessTeam
        :visible="editTeamVisible"
        :personnelInfo="personnelInfo"
        @handleCancel="editTeamVisible = false"
        @success="SetBusinessSuccess"
    />

    <!-- 线索列表 -->
    <CheckClueDetail
        :visible="showClue"
        :uid="uid"
        sourceType="user"
        @closeDetail="closeDetail"
    />

    <!-- 客户列表 -->
    <CheckUserDetail
        :visible="showCustomer"
        :uid="uid"
        sourceType="user"
        @closeDetail="closeDetail"
    />

    <!-- 合同列表 -->
    <ChannelDetail
        :visible="showContract"
        :uid="uid"
        sourceType="user"
        @closeDrawer="closeDetail"
    />

    <UserDetail
        @request="$utils.commonRequest"
        :visible="userVisible"
        :uid="uid"
        :coordinateData="coordinateData"
        @cancel="closeDetail"
    />
  </div>
</template>

<script>
import {
  reactive,
  ref,
  toRefs,
  computed,
  watch,
  defineComponent,
  createVNode,
} from "vue";
import request from "../../../../common/utils/request";
import {useRoute, useRouter} from "vue-router";
import {UserDetail} from "bl-common-vue3";
import store from "@/store";
import {Form, message, Modal} from "ant-design-vue";
import {ExclamationCircleOutlined, FormOutlined} from "@ant-design/icons-vue";

const useForm = Form.useForm;
import SetBusinessTeam from "@/views/village/BusinessManage/modules/SetBusinessTeam.vue";
import AddTeamPersonnel from "@/views/village/BusinessManage/modules/AddTeamPersonnel.vue";
import ChannelDetail from "@/views/village/BusinessManage/modules/ChannelDetail.vue";
import CheckUserDetail from "@/views/village/BusinessManage/modules/CheckUserDetail.vue";
import CheckClueDetail from "@/views/village/BusinessManage/modules/CheckClueDetail.vue";

export default defineComponent({
  name: "BusinessPersonnel",
  props: {
    activeKey: {
      type: [Number, String],
      default: "",
    },
    villageOptions: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    CheckClueDetail,
    CheckUserDetail,
    ChannelDetail,
    FormOutlined,
    SetBusinessTeam,
    AddTeamPersonnel,
    UserDetail,
  },
  setup(props, {emit}) {
    const state = reactive({
      dataList: [],
      columns: COLUMNS,
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      addVisible: false,
      editTeamVisible: false,
      personnelInfo: {},
      uid: 0,
      showClue: false,
      showCustomer: false,
      showContract: false,
      coordinateData: {},
      userVisible: false,
      expandedRowKeys: []
    });

    const searchParams = reactive({
      name: "",
      tel: "",
    });

    const {resetFields} = useForm(searchParams, {});

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const getDataList = (init = false) => {
      state.loading = true;
      state.expandedRowKeys = [];
      if (init) {
        state.page = 1;
      }
      const params = {
        page: state.page,
        pageSize: state.limit,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }

      request
          .get("/org", "/business/customerTeam/teamUserList", params)
          .then((res) => {

            state.dataList = res.list.map(item => {
              const children = []
              for (let i = 0; i < item.childrenCount; i++) {
                children.push({})
              }
              return {
                ...item,
                children: children
              }
            })

            state.total = res?.total || 0;
          })
          .finally(() => {
            state.loading = false;
          });
    };

    const getSubData = (expanded, record) => {
      console.log(expanded, record)
      if (!expanded) {
        state.expandedRowKeys.splice(
            state.expandedRowKeys.indexOf(record.id),
            1
        );
        return
      }
      state.expandedRowKeys.push(record.id)
      const param = {
        team_id: record.team_id,
        leader_uid: record.team.leader_uid
      }
      request.get("/org", "/business/customerTeam/teamUserArr", param).then(res => {
        console.log(res)
        record.children = res.data
      })

    }

    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    const reset = () => {
      resetFields();
      getDataList(true);
    };

    const addPersonnel = () => {
      state.addVisible = true;
    };

    // 人员修改团队信息
    const editTeam = (record) => {
      state.personnelInfo = record;
      state.editTeamVisible = true;
    };

    const SetBusinessSuccess = () => {
      state.editTeamVisible = false;
      getDataList();
    };

    const handleAddSuccess = () => {
      state.addVisible = false;
      getDataList();
    };

    const handleRemovePersonnel = (record) => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要移除所选人员吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          state.loading = true;
          request
              .del("/org", "/business/customerTeam/removeUser", {
                ids: String(record.id),
              })
              .then((res) => {
                message.success(res.msg || "移除成功!");
                getDataList();
              });
        },
      });
    };

    const showClueList = (val) => {
      state.uid = val;
      state.showClue = true;
    };

    const showCustomerList = (val) => {
      state.uid = val;
      state.showCustomer = true;
    };

    const toContractInfo = (val) => {
      state.uid = val;
      state.showContract = true;
    };

    const closeDetail = () => {
      state.uid = 0;
      state.showClue = false;
      state.showCustomer = false;
      state.showContract = false;
      state.userVisible = false;
    };

    const showUserInfo = (val) => {
      if (!val) {
        return;
      }
      state.uid = val;
      state.coordinateData = window.event;
      setTimeout(() => {
        state.userVisible = true;
      }, 50);
    };

    const init = () => {
      getDataList(true);
    };

    watch(
        () => props.activeKey,
        (val) => {
          if (val == 1) {
            init();
          }
        },
        {immediate: true}
    );

    return {
      ...toRefs(state),
      pagination,
      searchParams,
      handleTableChange,
      reset,
      getDataList,
      addPersonnel,
      editTeam,
      SetBusinessSuccess,
      handleAddSuccess,
      handleRemovePersonnel,
      showClueList,
      showCustomerList,
      toContractInfo,
      closeDetail,
      showUserInfo,
      getSubData
    };
  },
});

const COLUMNS = [
  {
    title: "招商人名称",
    align: "center",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "招商人电话",
    align: "center",
    dataIndex: "tel",
    key: "tel",
    customRender: ({text, record, index}) => {
      return record?.userInfo?.final_phone || "--";
    },
  },
  {
    title: "所属团队",
    align: "center",
    dataIndex: "teamName",
    key: "teamName",
  },
  {
    title: "线索数量",
    align: "center",
    dataIndex: "clue_num",
    key: "clue_num",
  },
  {
    title: "意向客户数量",
    align: "center",
    dataIndex: "customer_num",
    key: "customer_num",
  },
  {
    title: "合同数量",
    align: "center",
    dataIndex: "contract_num",
    key: "contract_num",
  },
  {
    title: "操作",
    align: "center",
    dataIndex: "id",
    key: "action",
    width: 180,
  },
];
</script>

<style lang="less" scoped>
.box {
  padding: 0 10px 10px 10px;

  .header-clue {
    padding: 0 14px;
  }

  .header-box {
    background: #fff;
    padding: 14px 10px;

    p {
      &:last-of-type {
        margin-bottom: 0;
      }
    }
  }

  .header {
    background-color: rgb(240, 242, 245);
    padding: 16px 10px;

    .num-info {
      color: @primary-color;
      font-size: 30px;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }
  }

  .header-content {
    width: 0;
  }
}

:deep(.ant-tabs-content) {
  height: 100%;
}

:deep(.ant-table-title) {
  padding: 0;
}

:deep(.ant-alert-description) {
  font-size: 12px;

  p {
    margin-bottom: 6px;
  }
}

:deep(.ant-alert-with-description.ant-alert-no-icon) {
  padding: 6px 10px;
}

.person-table {
  &:deep(.ant-table) {
    color: rgba(0, 0, 0, 85);

    .ant-table-tbody tr:nth-child(2n) td {
      background-color: #f2f3f3 !important;
    }
  }

  &:deep(.ant-table-row-level-1) {
    font-size: 13px;
    background-color: #f2f3f3 !important;
  }
}

</style>
